package com.qupeng.demo.kafka.kafkaspringbootproducer.avro;

import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;

import java.io.File;
import java.io.IOException;

public class TestAvroSerialization {

    public static void main(String[] args) {
        Product product1 = new Product();
        product1.setId(0);
        product1.setName("iPhone16");

        Product product2 = new Product(1, "Huawei");

        Product product3 = Product.newBuilder().setId(2).setName("Xiaomi").build();

        // 序列化product到文件中  
        DatumWriter<Product> productDatumWriter = new SpecificDatumWriter<Product>(Product.class);
        DataFileWriter<Product> dataFileWriter = new DataFileWriter<Product>(productDatumWriter);
        try {
            dataFileWriter.create(Product.getClassSchema(), new File("src/main/resources/avro/products.avro"));
            dataFileWriter.append(product1);
            dataFileWriter.append(product2);
            dataFileWriter.append(product3);
            dataFileWriter.flush();
            dataFileWriter.close();
        } catch (IOException e) {
        }

        // 从文件中反序列化对象  
        DatumReader<Product> productDatumReader = new SpecificDatumReader<Product>(Product.class);
        DataFileReader<Product> dataFileReader = null;
        try {
            dataFileReader = new DataFileReader<Product>(new File("src/main/resources/avro/products.avro"), productDatumReader);
        } catch (IOException e) {
        }
        Product product = null;
        try {
            while (dataFileReader.hasNext()) {
                product = dataFileReader.next(product);
                System.out.println(product);
            }
        } catch (IOException e) {
        }
    }
}